//
//  MyFirendDataManager.m
//  安好
//
//  Created by 马晓良 on 14-12-3.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyFirendDataManager.h"
@interface MyFirendDataManager ()
@property (nonatomic, strong) NSArray *engLishAlphabetArr;
//@property (nonatomic, strong) NSString *englishAlphabetStr;
/**
 *  获取指定字符串的拼音形式
 */
- (NSString *)_generateCaptialLetterWithString:(NSString *)string;
@end

@implementation MyFirendDataManager

- (NSMutableDictionary *)firendDic{
    if (_firendDic == nil) {
        self.firendDic = [NSMutableDictionary dictionary];
    }
    return _firendDic;
}

//- (NSString *)englishAlphabetStr{
//    if (_englishAlphabetStr == nil) {
//        _englishAlphabetStr = [NSString stringWithFormat:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
//    }
//    return _englishAlphabetStr;
//}

- (NSArray *)engLishAlphabetArr{
    if (_engLishAlphabetArr == nil) {
        _engLishAlphabetArr = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z", nil];
    }
    return _engLishAlphabetArr;
}

+ (id)shareInstance{
    static MyFirendDataManager *myFirendManager = nil;
    if (myFirendManager == nil) {
        myFirendManager = [[MyFirendDataManager alloc] init];
    }
    return myFirendManager;
}

- (NSInteger)numberOfFirendItems{
    NSInteger count = 0;
    for (NSString *key in self.firendDic) {
        count += [[self.firendDic objectForKey:key] count];
    }
    return count;
}


- (NSInteger)numberOfSections{
    return self.firendDic.count;
}

- (NSString *)titleStringForSection:(NSInteger)section{
    NSArray *orderedArray = [self.firendDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    
    return [orderedArray objectAtIndex:section];
}


- (MyFirendData *)firendItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *keyString = [NSString stringWithFormat:@"%@",[self titleStringForSection:indexPath.section - 1]];
    return [[self.firendDic objectForKey:keyString] objectAtIndex:indexPath.row];
}


- (NSInteger)numberOfFirendItemsInSection:(NSInteger)section{
    NSString *keyString = [NSString stringWithFormat:@"%@",[self titleStringForSection:section]];
    return [[self.firendDic objectForKey:keyString] count];
}


- (NSString *)_generateCaptialLetterWithString:(NSString *)string{
    
    NSMutableString *preString = [NSMutableString stringWithString:string];
    //变成不带音调的
    CFStringTransform((CFMutableStringRef)preString, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)preString, NULL, kCFStringTransformStripDiacritics, NO);

    return preString;
}

//  添加好友对象
- (void)addNewFirendItem:(MyFirendData *)item{
    NSString *pinyinString = [NSString stringWithFormat:@"%@",[self _generateCaptialLetterWithString:item.username]];
    NSString *tempStr = [pinyinString substringToIndex:1];
    NSString *keyString = [tempStr uppercaseString];
    NSString *keyStr = [NSString stringWithFormat:@"%@",keyString];
    NSMutableArray *objectArray;
//    if (self.englishAlphabetStr != nil) {
//        if ([self.englishAlphabetStr containsString:keyStr]) {
//            objectArray = [self.firendDic objectForKey:keyStr];
//        }else{
//            objectArray = [self.firendDic objectForKey:@"#"];
//        }
//        if ([self.englishAlphabetStr containsString:keyStr]) {
//            if (objectArray == nil) {
//                objectArray = [NSMutableArray array];
//                [self.firendDic setObject:objectArray forKey:keyStr];
//            }
//        }else{
//            if (objectArray == nil) {
//                objectArray = [NSMutableArray array];
//                [self.firendDic setObject:objectArray forKey:@"#"];
//                MyNSLog("************%@", objectArray);
//                MyNSLog("点我了");
//            }
//        }
    if (self.engLishAlphabetArr != nil) {
        if ([self.engLishAlphabetArr containsObject:keyStr]) {
            objectArray = [self.firendDic objectForKey:keyStr];
        }else{
            objectArray = [self.firendDic objectForKey:@"#"];
        }
        if ([self.engLishAlphabetArr containsObject:keyStr]) {
            if (objectArray == nil) {
                objectArray = [NSMutableArray array];
                [self.firendDic setObject:objectArray forKey:keyStr];
            }
        }else{
            if (objectArray == nil) {
                objectArray = [NSMutableArray array];
                [self.firendDic setObject:objectArray forKey:@"#"];
                MyNSLog("************%@", objectArray);
                MyNSLog("点我了");
            }
        }
     [objectArray addObject:item];
    }else{
        MyNSLog("空");
    }
    
}

- (void)deleteFirendItem:(MyFirendData *)item{
    NSString *pinyinString = [NSString stringWithFormat:@"%@",[self _generateCaptialLetterWithString:item.username]];
    NSString *tempStr = [pinyinString substringToIndex:1];
    NSString *keyString = [tempStr uppercaseString];
    NSString *keyStr = [NSString stringWithFormat:@"%@",keyString];
    NSMutableArray *objectArray;
    if (self.engLishAlphabetArr != nil) {
        if ([self.engLishAlphabetArr containsObject:keyStr]) {
            objectArray = [self.firendDic objectForKey:keyStr];
        }else{
            objectArray = [self.firendDic objectForKey:@"#"];
        }
        if ([self.engLishAlphabetArr containsObject:keyStr]) {
            if (objectArray == nil) {
                objectArray = [NSMutableArray array];
                [self.firendDic setObject:objectArray forKey:keyStr];
            }
        }else{
            if (objectArray == nil) {
                objectArray = [NSMutableArray array];
                [self.firendDic setObject:objectArray forKey:@"#"];
                MyNSLog("点我了");
            }
        }
        [objectArray removeObject:item];
    }
    
}

#pragma mark - 对头像进行操作 -
// imagePath存放图片的地址
- (NSString *)getImagePath:(NSString *)imagePathUid withMyUid:(NSString *)myuid{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // 拼接出来的图片名字
    NSString *imagesPath = [documentPath stringByAppendingString:[NSString stringWithFormat:@"/MyFirendsHeaderImage/%@%@",imagePathUid,myuid]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:imagesPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:imagesPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *changeUrl = [NSString stringWithFormat:@"%@%@.png",imagePathUid,myuid];
    return [imagesPath stringByAppendingPathComponent:changeUrl];
}

// 获取本地图片
- (UIImage *)loadImageFromDocument:(NSString *)uid withMyUid:(NSString *)myuid{
    NSString *imagePathOfLocation = [self getImagePath:uid withMyUid:myuid];
    // 获取图片的二进制字节流
    NSData *image_data = [NSData dataWithContentsOfFile:imagePathOfLocation];
    // 生成图片
    UIImage *image = [UIImage imageWithData:image_data];
    return image;
}

//  存入本地
- (void)setImagePath:(NSString *)path withUid:(NSString *)uid withMyUid:(NSString *)myuid{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *image_path = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
        NSString *imagePath = [self getImagePath:uid withMyUid:myuid];
        //图片写入本地
        [image_path writeToFile:imagePath atomically:NO];
        });
}

- (void)deleteImage:(NSString *)firendId withMyUid:(NSString *)myuid{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *imageFileName = [NSString stringWithFormat:@"/MyFirendsHeaderImage/%@%@",firendId,myuid];
    NSString *filePath = [documentPath stringByAppendingPathComponent:imageFileName];
    MyNSLog("%@", filePath);
    //假如存在文件夹，那么就删除对应的文件夹
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
}


- (BOOL)judgeImageExist:(NSString *)uid withMyUid:(NSString *)myuid{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // 拼接出来的图片名字
    NSString *imagesPath = [documentPath stringByAppendingString:[NSString stringWithFormat:@"/MyFirendsHeaderImage/%@%@",uid,myuid]];
    NSString * imageName = [NSString stringWithFormat:@"/%@%@.png",uid,myuid];
    NSString *str = [imagesPath stringByAppendingPathComponent:imageName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
     BOOL result = [fileManager fileExistsAtPath:str];
    return result;
}

#pragma mark - 数据库 -NONCLUSTERED
- (void)createTableWithName:(NSString *)name{
    sqlite3 *database = [self open_database];
    NSString *sql = [NSString stringWithFormat:@"create table if not exists %@ (uid text, myuid text, avatar text, username text, primary key(uid, myuid))",name];
    // 执行数据库语句
    sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL);
}

- (void)addNewFirendInfo:(MyFirendData *)oneMyFirend{
    sqlite3 *database = [self open_database];
    NSString *sqlString = [NSString stringWithFormat:@"insert into myFirendTable (uid,myuid,avatar,username) values ('%@','%@','%@','%@')",oneMyFirend.uid,oneMyFirend.myuid,oneMyFirend.avatar,oneMyFirend.username];
    sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, NULL);
}

- (NSArray *)searchMyFirendInfo:(NSString *)myuid{
    sqlite3 *database = [self open_database];
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select * from myFirendTable where myuid = '%@'",myuid];
    // 声明数据集指针
    sqlite3_stmt *statment = nil;
    sqlite3_prepare_v2(database, [sql UTF8String], -1, &statment, NULL);
    while (sqlite3_step(statment) == SQLITE_ROW) {
        
        //获得uid
        const unsigned char *cfirst = sqlite3_column_text(statment, 0);
        NSString *uid = [NSString stringWithCString:(const char *)cfirst encoding:NSUTF8StringEncoding];
        
        //获得我的uid
        const unsigned char *cSecond = sqlite3_column_text(statment, 1);
        NSString *myuid = [NSString stringWithCString:(const char *)cSecond encoding:NSUTF8StringEncoding];
        
        //获得图片地址
        const unsigned char *cThird = sqlite3_column_text(statment, 2);
        NSString *avatar = [NSString stringWithCString:(const char *)cThird encoding:NSUTF8StringEncoding];
        
        //获得好友名字
        const unsigned char *cFour = sqlite3_column_text(statment, 3);
        NSString *userName = [NSString stringWithCString:(const char *)cFour encoding:NSUTF8StringEncoding];
        
        MyFirendData *item = [[MyFirendData alloc] init];
        item.uid = uid;
        item.myuid = myuid;
        item.avatar = avatar;
        item.username = userName;
        [array addObject:item];;
        
    }
    sqlite3_finalize(statment);//完成后就释放statmment
    return array;
}


- (NSArray *)searchMYfirendInfoWithUid:(NSString *)myuid withString:(NSString *)str{
    sqlite3 *database = [self open_database];
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select * from myFirendTable where myuid = '%@' and username like '%%%@%%'",myuid,str];
    // 声明数据集指针
    sqlite3_stmt *statment = nil;
    sqlite3_prepare_v2(database, [sql UTF8String], -1, &statment, NULL);
    while (sqlite3_step(statment) == SQLITE_ROW) {
        
        //获得uid
        const unsigned char *cfirst = sqlite3_column_text(statment, 0);
        NSString *uid = [NSString stringWithCString:(const char *)cfirst encoding:NSUTF8StringEncoding];
        
        //获得我的uid
        const unsigned char *cSecond = sqlite3_column_text(statment, 1);
        NSString *myuid = [NSString stringWithCString:(const char *)cSecond encoding:NSUTF8StringEncoding];
        
        //获得图片地址
        const unsigned char *cThird = sqlite3_column_text(statment, 2);
        NSString *avatar = [NSString stringWithCString:(const char *)cThird encoding:NSUTF8StringEncoding];
        
        //获得好友名字
        const unsigned char *cFour = sqlite3_column_text(statment, 3);
        NSString *userName = [NSString stringWithCString:(const char *)cFour encoding:NSUTF8StringEncoding];
        
        MyFirendData *item = [[MyFirendData alloc] init];
        item.uid = uid;
        item.myuid = myuid;
        item.avatar = avatar;
        item.username = userName;
        
        [array addObject:item];
    }
    sqlite3_finalize(statment);//完成后就释放statmment
    return array;
}

// 删除 myFirend数据
- (void)deleteMyFirendInfo:(NSString *)firendObjcUid withMyUid:(NSString *)myuid{
    sqlite3 *database = [self open_database];
    NSString *sql = [NSString stringWithFormat:@"delete from myFirendTable where uid = '%@' and myuid = '%@'",firendObjcUid,myuid];
    sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL);
}

// 更新数据
- (void)updateMyFirendInfo:(MyFirendData *)firendObjc{
//    sqlite3 *database = [self open_database];
//    NSString *sql = [NSString stringWithFormat:@"update from myFirendTable where uid = '%@' and myuid = '%@'",firendObjc.uid,firendObjc.myuid];
//    sqlite3_stmt *statment = nil;
//    sqlite3_prepare_v2(database, [sql UTF8String], -1, &statment, NULL);
//    while (sqlite3_step(statment) == SQLITE_ROW){
//        
//    }
}


- (void)deleteMyFirendInfo:(NSString *)myuid{
    sqlite3 *database = [self open_database];
    NSString *sql = [NSString stringWithFormat:@"delete from myFirendTable where myuid = '%@'",myuid];
    sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL);
}



- (void)deleteMyfirendTable{
    sqlite3 *database = [self open_database];
    NSString *sql = [NSString stringWithFormat:@"drop table if exists myFirendTable"];
    sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL);
}


@end


@implementation MyFirendDataManager (MyFirendDataOperation)

- (NSString *)databaseFilePathName:(NSString *)databaseName{
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [document stringByAppendingPathComponent:databaseName];
    MyNSLog("%@", filePath);
    return filePath;
}

- (sqlite3 *)open_database{
    NSString *dataPath = [self databaseFilePathName:@"DownloadFirendDatabase.sqlite"];
    static sqlite3 *database = nil;
    if (database == nil) {
        sqlite3_open([dataPath UTF8String], &database);
    }
    return database;
}



@end
